import path from "path";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from '@tailwindcss/vite'
import postcssPresetEnv from 'postcss-preset-env'
import postcssDiscard from 'postcss-discard'
import wsjpre from './wsjpre.js'; // 引入自定义插件
import wsjpost from './wsjpost.js'; // 引入自定义插件
export default ({ mode }) => {
  const ENV_OBJ = loadEnv(mode, process.cwd())
  console.log('======mode', mode);
  function isDevMode() {
    return mode === 'development'
  }
  //development和production
  return defineConfig({
    base: ENV_OBJ.VITE_Base_URL,
    plugins: [react(), tailwindcss(), isDevMode() && wsjpost()],
    css: {
      postcss: {
        plugins: [
          ...(isDevMode() ? [postcssPresetEnv()] : [])
        ]
      }
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src")
      }
    },
    publicDir: ENV_OBJ.VITE_Public_Dir,
    server: {
      open: ENV_OBJ.VITE_Base_URL,
      proxy: {
        [ENV_OBJ.VITE_API_PREFIX]: {
          // 用于开发环境下的转发请求1
          // 更多请参考：https://vitejs.dev/config/#server-proxy
          target: ENV_OBJ.VITE_proxy_target,
          changeOrigin: true
        },
        "/bartech_qa_author_api": {
          // 用于开发环境下的转发请求
          // 更多请参考：https://vitejs.dev/config/#server-proxy
          target: ENV_OBJ.VITE_proxy_target,
          changeOrigin: true
        },
        "/wsj": {
          // 用于开发环境下的转发请求
          // 更多请参考：https://vitejs.dev/config/#server-proxy
          target: "http://localhost:3010",
          changeOrigin: true
        }
      }
    },
    build: {
      outDir: ENV_OBJ.VITE_DIST,
      assetsInlineLimit: 4096,//字体小于4kb,则直接转成base64
      rollupOptions: {
        output: {
          manualChunks: {
            "react-vendor": ["react", "react-dom"],
            //zarmhaha: ["zarm"]
          },
          entryFileNames: "js/[name].[hash].js",
          chunkFileNames: "js/[name].[hash].js",
          //字符串形式的配置assetFileNames: "[ext]/[name].[hash].[ext]"
          assetFileNames: (assetInfo) => {
            /*
            [extname]是带点,如.css
            [ext]不带点,如css
            */
            if (/\.(ttf|woff|woff2)$/.test(assetInfo.names[0])) {
              return `fonts/[name].[hash][extname]`;
            }
            if (assetInfo.names[0].endsWith('.css')) {
              return 'css/[name].[hash].css'
            }
            if (['.png', '.jpg', '.jpeg', '.webp', '.svg', '.gif'].some(ext => assetInfo.names[0].endsWith(ext))) {
              return 'img/[name].[hash].[ext]'
            }
            // 对于其他类型的文件，你可以继续添加更多的条件判断  
            // ...  

            // 如果没有匹配到任何条件，则使用默认的输出路径和命名规则  
            return `assets/[name]-[hash][extname]`;
          },
        }
      }
    }
  })
};
